﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Configuration;
using iSun.Entity;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.ComponentModel;
using iSun.App;
using System.Net;

namespace iSun.App
{
    [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]//　　注意： 类定义前需要加上下面两行，否则调用失败！
    [System.Runtime.InteropServices.ComVisibleAttribute(true)] 
    public partial class MainFrom : Form
    {
        private iSun.App.DataSerivce.vendor vendor;
        private Guid CurrentProductID=Guid.Empty;
        public MainFrom()
        {
            InitializeComponent();
            webBrowser1.ObjectForScripting = new ScriptManager(this);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            DataAction.UploadSourceFile(0);
            MessageBox.Show("上传成功");
        }

        private void MainFrom_Load(object sender, EventArgs e)
        {
            this.webBrowser1.Url = new Uri(ConfigurationManager.AppSettings["step1URL"]);
            //this.webBrowser2.Url = new Uri(ConfigurationManager.AppSettings["step2URL"]);
            this.WindowState = FormWindowState.Maximized;

            if (ConfigurationManager.AppSettings["timeSpan"] != string.Empty)
            {
                timer1.Interval = Convert.ToInt32(ConfigurationManager.AppSettings["timeSpan"]);
            }
            timer1.Start();

            _updateLabel = (curr, total) => { lblInfo.Text = string.Format("{0}KB/{1}KB", curr / 1000, total / 1000); };
            _updateProcessBar = (process) => { progressBar1.Value = process; };
            _updateFileName = (filename) => { lblFileName.Text = filename; };
            IList<iSun.App.DataSerivce.vendor> list = DataAction.GetVendorList();
            //comboBox1.Items.Add("");
            foreach (iSun.App.DataSerivce.vendor vendor in list)
            {
                comboBox1.Items.Add(vendor.id + "_" + vendor.name);
            }

            #region
            bool _isAdmin = (ConfigurationManager.AppSettings["IsAdmin"] == "Y");

            this.btnCancelCaption.Visible = _isAdmin;
            this.btnInitData.Visible = _isAdmin;
            this.btnInitDirName.Visible = _isAdmin;
            this.cbkInitDataFlag.Visible = _isAdmin;
            this.btnUploadSourceFile.Visible = _isAdmin;
            this.btnUploadInitFiles.Visible = _isAdmin;
            //this.btnModifyFolder.Visible = _isAdmin;
            #endregion
            //this.tableLayoutPanel1.RowStyles[0].Height = (float)(50);
        }



        private void button2_Click(object sender, EventArgs e)
        {
            DataAction.UploadSourceFile(1);
            MessageBox.Show("上传成功");
        }


        private bool CheckIsExists(string SN)
        {
            WebClient MyWebClient = new WebClient();
            MyWebClient.Credentials = CredentialCache.DefaultCredentials;//获取或设置用于对向Internet资源的请求进行身份验证的网络凭据。
            string url = ConfigurationManager.AppSettings["SeverURL"]+string.Format("/Extend/AjaxData/DataTableJsonList.aspx?type=1&entity=V_Gs_Product&condition=SN='{0}' and id like '%_{1}'",SN,this.comboBox1.Text.Trim().Split('_')[0]);
            Byte[] pageData = MyWebClient.DownloadData(url);
            string data = System.Text.Encoding.UTF8.GetString(pageData);
            return data == "[]";
        }

        public IList<iSun.Entity.ProductPhotoEnitty> GetProduct(string productID)
        {
            return DataAction.GetProduct(productID);
            //WebClient MyWebClient = new WebClient();
            //MyWebClient.Credentials = CredentialCache.DefaultCredentials;//获取或设置用于对向Internet资源的请求进行身份验证的网络凭据。
            //string url = ConfigurationManager.AppSettings["SeverURL"] + string.Format("/Extend/AjaxData/DataTableJsonList.aspx?type=1&entity=Gs_Product&condition=id= '{0}'",productID);
            //Byte[] pageData = MyWebClient.DownloadData(url);
            //string data = System.Text.Encoding.UTF8.GetString(pageData);

            //ZX.Log.XTrace.WriteLine("----------------------------上传---begin---------------------------------");
            //ZX.Log.XTrace.WriteLine(System.DateTime.Now.ToString());
            //ZX.Log.XTrace.WriteLine(url);
            //ZX.Log.XTrace.WriteLine(data);
            //ZX.Log.XTrace.WriteLine("-------------------------------end-----------------------------------");

            //if (data == "[]")
            //{
            //    return null;
            //}
            //IList<iSun.Entity.ProductPhotoEnitty> list = new List<iSun.Entity.ProductPhotoEnitty>();
            //var entity = ZX.Common.Globals.JSonToObject<iSun.Entity.ProductPhotoEnitty>(data.Replace("[[", "").Replace("]]", ""));
            //if (entity != null)
            //{
            //    list.Add(entity);
            //}
            //return list;
        }

        private void txtSN_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r' && txtSN.Text.Trim()!=string.Empty)
            {
                //MessageBox.Show(e.KeyChar.ToString());
                iSun.UpLoadServiceClient ser = new iSun.UpLoadServiceClient();
                iSun.IUpLoadService channel = ser.ChannelFactory.CreateChannel();
                if (chkNewStatus.Checked)
                {
                    if (string.IsNullOrEmpty(this.comboBox1.Text))
                    {
                        //if (channel.IsExistsProduct(txtSN.Text))

                        MessageBox.Show("请选择供应商！", "提示");
                        return;
                    }
                    if (!CheckIsExists(txtSN.Text))
                    {
                        MessageBox.Show("该产品条码己经存在！", "提示");
                        webBrowser1.Document.InvokeScript("show");
                    }
                    IList<ProductPhotoEnitty> list = new List<ProductPhotoEnitty>();
                    ProductPhotoEnitty pEntity = new ProductPhotoEnitty();
                    pEntity.SN = txtSN.Text;
                    pEntity.ProductName = txtSN.Text;
                    pEntity.ID = new Guid();
                    pEntity.AddTime = System.DateTime.Now;
                    pEntity.AddUser = Guid.Empty;
                    pEntity.Vendor_id = comboBox1.Text == "" ? 0 : Convert.ToInt32(comboBox1.Text.Split('_')[0]);
                    list.Add(pEntity);
                    channel.UploadProduct(ZX.Common.Globals.ListToJson<ProductPhotoEnitty>(list));

                    DataAction.CreateProductDir(txtSN.Text + "_" + this.comboBox1.Text.Split('_')[0]);
                }
                else
                {
                    if (CheckIsExists(txtSN.Text))
                    {
                        MessageBox.Show("该产品条码不存在！", "提示");
                        return;
                    }

                }
                this.webBrowser1.Document.GetElementById("NewStatus").SetAttribute("value", this.chkNewStatus.Checked.ToString());
                this.webBrowser1.Document.GetElementById("SN").SetAttribute("value", txtSN.Text);
                webBrowser1.Document.InvokeScript("show");
                this.txtSN.Focus();
                this.txtSN.SelectAll();
                this.txtSN.Text = "";
            }
        }

        [ComVisible(true)]
        public class ScriptManager
        {
            MainFrom _form;
            public ScriptManager(MainFrom form)
            {
                _form = form;
            }
            public void ShowMessage(object obj)
            {
                MessageBox.Show(obj.ToString());
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            (new iSun.App.frmEditConfig()).Show();
        }

        private void txtSN_TextChanged(object sender, EventArgs e)
        {

        }

        private void txtSN_Enter(object sender, EventArgs e)
        {
            this.txtSN.SelectAll();
        }

        private void chkNewStatus_CheckedChanged(object sender, EventArgs e)
        {
            this.webBrowser1.Document.GetElementById("NewStatus").SetAttribute("value", this.chkNewStatus.Checked.ToString());
        }

        /// <summary>
        /// 删除相片
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDeleteProduct_Click(object sender, EventArgs e)
        {
            string SN = this.webBrowser1.Document.GetElementById("SN").GetAttribute("value");
            string ProductID = this.webBrowser1.Document.GetElementById("SN").GetAttribute("value");
            if (MessageBox.Show("是否删除" + SN + "?","确认", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
            {
                string sourceURL = ConfigurationManager.AppSettings["filePath"];
                try
                {
                    iSun.Entity.ProductPhotoEnitty entity = GetProduct(ProductID)[0];
                    string _path = sourceURL + entity.SN + "_" + entity.Vendor_id;
                    if (System.IO.Directory.Exists(_path))
                    {
                        System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(_path);
                        dir.Delete(true);
                    }
                }
                catch (Exception e1)
                {
                }

                try
                {
                    iSun.UpLoadServiceClient ser = new iSun.UpLoadServiceClient();
                    iSun.IUpLoadService channel = ser.ChannelFactory.CreateChannel();
                    channel.DeleteProuct(ProductID);
                }
                catch (Exception e1)
                {

                }
                webBrowser1.Document.InvokeScript("DeleteNodes");
                MessageBox.Show("产品删除成功！");
            }
        }

        private void OpenFolder(string path)
        {
            if (System.IO.Directory.Exists(path))
            {
                System.Diagnostics.Process.Start("explorer.exe", path);
            }
            else
            {
                MessageBox.Show("没有相关文件夹！");
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            string o = webBrowser1.Document.InvokeScript("GetSelectedImages") as string;
            if (o == "")
            {
                return;
            }

            if (MessageBox.Show("是否删除选定的图片?", "确认", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
            {
                //string o = webBrowser1.Document.InvokeScript("GetSelectedImages") as string;
                DeleteImages(o);
                DataAction.DeleteImages(o);
                MessageBox.Show("产品图片删除成功！");
                webBrowser1.Document.InvokeScript("fnRefresh");
            }
        }

        private void DeleteImages(string images)
        {
            string[] imagePath = images.Split(',');
            //ZX.BLL.Extend.BaseBussnies bll = new ZX.BLL.Extend.BaseBussnies();
            foreach (string _image in imagePath)
            {
                string Path1= ConfigurationManager.AppSettings["filePath"];
                string Path2 = ConfigurationManager.AppSettings["filePath1"];
                string filePath = "";
                if (_image.ToLower().Contains("\\upload\\photo1"))
                {
                  filePath =  Path2+  _image.ToLower().Replace("\\upload\\photo1\\", "");
                }
                else
                {
                    filePath = Path1 + _image.ToLower().Replace("\\upload\\photo\\", "");
                }
                string _path = ZX.Common.FileHelper.GetFileDir(filePath);
                string _filename = ZX.Common.FileHelper.GetFileNameNoPath(filePath);

                string _filePath = _path + "\\uploaded_" + _filename;
                //webPath = webPath + _image;
                if (System.IO.File.Exists(_filePath))
                {
                    System.IO.File.Delete(_filePath);
                }
                //ZX.Common.FileHelper.GetFileDir(
                //bll.RunSqlCommand(string.Format("delete from gs_ProductImage where FilePath='{0}';", _image));
            }
        }
        
        private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {

        }

        #region 打开目录
        private void OpenFolder()
        {
            string sourcePath = ConfigurationManager.AppSettings["downModifiedFile"];
            string SN = this.webBrowser1.Document.GetElementById("SN").GetAttribute("value");
            string[] _str = SN.Split('_');
            sourcePath = sourcePath + (SN.Length > 36 ? _str[1] : SN);
            string productID = this.webBrowser1.Document.GetElementById("CurrentProductID").GetAttribute("value");
            string vendorID = this.webBrowser1.Document.GetElementById("CurrentProductID").GetAttribute("CurrentVendor_ID");
            MessageBox.Show(productID);
            if (!System.IO.Directory.Exists(sourcePath))
            {

                var list = GetProduct(productID);
                if (list == null)
                {
                    
                    sourcePath = sourcePath + "_" + vendorID==""? this.comboBox1.Text.Trim().Split('_')[0]:vendorID;
                }
                else
                {
                    sourcePath = sourcePath + "_" + list[0].Vendor_id.ToString();
                }
            }
            else
            {
                string _sourcePath = "";
                //productID = _str[0];
                var list = GetProduct(productID);
                if (list == null)
                {
                    ZX.Log.XTrace.WriteLine("----------------------------上传---begin---------------------------------");
                    ZX.Log.XTrace.WriteLine(System.DateTime.Now.ToString());
                    ZX.Log.XTrace.WriteLine("实体转换出错！");
                    ZX.Log.XTrace.WriteLine("-------------------------------end-----------------------------------");
                    _sourcePath = sourcePath + "_" + this.comboBox1.Text.Trim().Split('_')[0];
                }
                else
                {
                    _sourcePath = sourcePath + "_" + list[0].Vendor_id.ToString();
                }
                if (System.IO.File.Exists(_sourcePath))
                {
                    sourcePath = _sourcePath;
                }
            }
            if (SN.Length > 36)
            {
                switch (_str[2])
                {
                    case "0":
                        sourcePath = sourcePath + "\\images\\";
                        //__ttype = "P";
                        break;
                    case "1":
                        sourcePath = sourcePath + "\\thumb\\";
                        //__ttype = "T";
                        break;
                    case "2":
                        sourcePath = sourcePath + "\\vedio\\";
                        //__ttype = "V";
                        break;
                    default:
                        sourcePath = sourcePath + "\\images\\";
                        //__ttype = "P";
                        break;
                }
            }
            OpenFolder(sourcePath);
        }

        private void OpenFolder(bool isSourceFolder)
        {
            string sourcePath = isSourceFolder ? ConfigurationManager.AppSettings["filePath"] : ConfigurationManager.AppSettings["filePath1"];
            string SN = this.webBrowser1.Document.GetElementById("SN").GetAttribute("value");
            string[] _str = SN.Split('_');
            sourcePath = sourcePath + (SN.Length > 36 ? _str[1] : SN);
            string productID = this.webBrowser1.Document.GetElementById("CurrentProductID").GetAttribute("value"); ;
            if (!System.IO.Directory.Exists(sourcePath))
            {
               
                var list = GetProduct(productID);

                if (list == null)
                {
                    sourcePath = sourcePath + "_" + this.comboBox1.Text.Trim().Split('_')[0];
                }
                else
                {
                    sourcePath = sourcePath + "_" + list[0].Vendor_id.ToString();
                }
            }
            else
            {
                string _sourcePath = "";
                //productID = _str[0];
                var list = GetProduct(productID);
                if (list == null)
                {

                    _sourcePath = sourcePath + "_" + this.comboBox1.Text.Trim().Split('_')[0];
                }
                else
                {
                    _sourcePath = sourcePath + "_" + list[0].Vendor_id.ToString();
                }
                if (System.IO.File.Exists(_sourcePath))
                {
                    sourcePath = _sourcePath;
                }
            }
            if (SN.Length > 36)
            {
                switch (_str[2])
                {
                    case "0":
                        sourcePath = sourcePath + "\\images\\";
                        //__ttype = "P";
                        break;
                    case "1":
                        sourcePath = sourcePath + "\\thumb\\";
                        //__ttype = "T";
                        break;
                    case "2":
                        sourcePath = sourcePath + "\\vedio\\";
                        //__ttype = "V";
                        break;
                    default:
                        sourcePath = sourcePath + "\\images\\";
                        //__ttype = "P";
                        break;
                }
            }
            MessageBox.Show(sourcePath);
            OpenFolder(sourcePath);
        }

        private void btnSourceFolder_Click(object sender, EventArgs e)
        {
            OpenFolder(true);
        }

        private void btnModifyFolder_Click(object sender, EventArgs e)
        {
            OpenFolder(false);
        }

        private void btnModifiedDownLandFileFloder_Click(object sender, EventArgs e)
        {
            OpenFolder();
        }
        #endregion

        #region 下载文件
        private void DownLandServerFile(bool isSourceFile)
        {
            string checkFlag = this.webBrowser1.Document.GetElementById("ckChoiceSN").GetAttribute("checked");
            if (checkFlag.ToLower() == "true")
            {
                string nodes = this.webBrowser1.Document.InvokeScript("GetCheckedItems") as string;
                if (!string.IsNullOrEmpty(nodes))
                {
                    string json = "[" + nodes + "]";
                    IList<iSun.Entity.ProductTemp> list = ZX.Common.Globals.JSonToObject<IList<iSun.Entity.ProductTemp>>(json);
                    (new DialogForm(list, isSourceFile)).Show();
                }
            }
            else
            {
                string SN = this.webBrowser1.Document.GetElementById("SN").GetAttribute("value");
                string Vendor_ID = this.webBrowser1.Document.GetElementById("CurrentVendor_ID").GetAttribute("value");
                string Product_ID = this.webBrowser1.Document.GetElementById("CurrentProductID").GetAttribute("value");
                if (string.IsNullOrEmpty(SN) || SN == "root")
                {
                    MessageBox.Show("请选择产品！", "提示");
                    return;
                }
                (new DialogForm(SN, Product_ID, Vendor_ID, isSourceFile)).Show();
            }
        }



        private void btnDownLandModifiedFile_Click(object sender, EventArgs e)
        {
            DownLandServerFile(false);
        }

        private void btnDownLandSourceFile_Click(object sender, EventArgs e)
        {
            DownLandServerFile(true);
        }

        #endregion

        #region  自动执行任务
        private void timer1_Tick(object sender, EventArgs e)
        {
            timer1.Stop();
            
            RunTask();

            timer1.Start();
        }

        /// <summary>
        /// 自动执行任务
        /// </summary>
        private void RunTask()
        {
            try
            {
                CurrentProductID = Guid.Empty;
                string _prouctid = this.webBrowser1.Document.GetElementById("CurrentProductID").GetAttribute("value");
                if (_prouctid != string.Empty)
                {
                    CurrentProductID = Guid.Parse(_prouctid);
                }
                UserInfo.CurrentProductID = CurrentProductID;
                UserInfo.CurrentVendor_id =    GetProduct(_prouctid)[0].Vendor_id.ToString();
                string SN = this.webBrowser1.Document.GetElementById("SN").GetAttribute("value");
                string[] _str = SN.Split('_');
                int flag = 0;
                if (SN != string.Empty)
                {
                    if (SN.Length > 36)
                    {
                        if (_str[2] == "2")//如果是视频
                        {
                            System.IO.FileInfo[] files = DataAction.MoveFile(out flag, SN);//获取所有文件
                            //files = DataAction.MoveFile(out flag, SN);//获取所有文件
                            
                            foreach (var fi in files)
                            {
                                //while (fi.Name != this.lblFileName.Text)
                                //{
                                //    continue;
                                //}
                                if (fi.Name.ToLower().Contains("uploaded"))
                                {
                                    continue;
                                }

                                UploadFile(fi, 0);
                            }
                            //this.tableLayoutPanel1.RowStyles[0].Height = (float)(50);
                        }
                        else
                        {
                           
                            DataAction.MoveFile(SN, out flag);
                            _uploadCompleted = true;
                        }
                    }
                    else
                    {
                        if (String.IsNullOrEmpty(SN))
                            return;
                        DataAction.MoveFile(SN, out flag);
                        _uploadCompleted = true;
                    }
                    if (flag == 1)
                    {
                        webBrowser1.Document.InvokeScript("fnRefresh");
                    }
                }
            }
            catch (Exception e1)
            {
            }
        }
        #endregion
        
        #region  上传视频文件

        private bool _uploadCompleted = false;
        private iSun.UpLoadServiceClient  _client = new iSun.UpLoadServiceClient();
        private System.Threading.Thread _uploadWatchThread;  
        private Action<int, int> _updateLabel;  
        private Action<int> _updateProcessBar;
        private Action<string> _updateFileName;

        /// <summary>
        /// 异步上传文件
        /// </summary>
        /// <param name="fi"></param>
        /// <param name="stepN"></param>
        public  void UploadFile(System.IO.FileInfo fi, int stepN)
        {
            #region 
            //if (fi.FullName.Contains("vedio"))
            //{
            //    if (!fi.Extension.Contains("zip"))
            //    {

            //        if (_filelenth > -1)
            //        {
            //            if (_fileIndex < _filelenth)
            //            {
            //                _fileIndex = _fileIndex + 1;
            //                UploadFile(_list[_fileIndex].file, _list[_fileIndex].stepN);
            //            }
            //        }
            //        return;
            //    }
            //}
            //if (fi.Name.ToLower().StartsWith("uploaded_"))
            //{
            //    if (_filelenth > -1)
            //    {
            //        if (_fileIndex < _filelenth)
            //        {
            //            _fileIndex = _fileIndex + 1;
            //            UploadFile(_list[_fileIndex].file, _list[_fileIndex].stepN);
            //        }
            //    }
            //    return;
            //}
            //if (stepN == 1 && ZX.Common.FileHelper.GetFileDir(fi.FullName).ToLower().Contains("\\source"))
            //{
            //    if (_filelenth > -1)
            //    {
            //        if (_fileIndex < _filelenth)
            //        {
            //            _fileIndex = _fileIndex + 1;
            //            UploadFile(_list[_fileIndex].file, _list[_fileIndex].stepN);
            //        }
            //    }
            //    return;
            //}
            //if (stepN == 1 && ZX.Common.FileHelper.GetFileDir(fi.FullName).ToLower().Contains("\\modified"))
            //{
            //    if (_filelenth > -1)
            //    {
            //        if (_fileIndex < _filelenth)
            //        {
            //            _fileIndex = _fileIndex + 1;
            //            UploadFile(_list[_fileIndex].file, _list[_fileIndex].stepN);
            //        }
            //    }
            //    return;
            //}
            #endregion
            try
            {
                string _path = stepN == 0 ? ConfigurationManager.AppSettings["filePath"] : ConfigurationManager.AppSettings["filePath1"];
                ProductImage entity = new ProductImage();

                entity.fileName = fi.Name;
                entity.FilePath = fi.FullName.Replace(_path, "").Replace(fi.Name, "");
                entity.SN = entity.FilePath.Split('\\')[0];
                entity.DirectoryName = fi.DirectoryName.Replace(_path, "");
                entity.FullName = fi.FullName;
                entity.StepN = stepN;

                entity.SourceFileName = fi.Name;
                entity.FileType = fi.Extension;

                entity.ImageType = "0";
                entity.ImageType = entity.FilePath.Contains("\\thumb\\") ? "1" : entity.ImageType;
                entity.ImageType = entity.FilePath.Contains("\\vedio\\") ? "2" : entity.ImageType;
                //entity.ImageType = 

                if (fi.Extension.ToLower().IndexOf("jpg") > -1)
                {
                    Fotofly.JpgPhoto jpgPhotoOne = ZX.Common.IPTC.ReadImageInfo.Load(fi.FullName);
                    entity.Summary = jpgPhotoOne.Metadata.Comment;
                    entity.CreationSoftware = jpgPhotoOne.Metadata.CreationSoftware;
                    entity.CameraManufacturer = jpgPhotoOne.Metadata.CameraManufacturer;
                    entity.CameraModel = jpgPhotoOne.Metadata.CameraModel;
                    entity.Copyright = jpgPhotoOne.Metadata.Copyright;
                    entity.HeigthPix = jpgPhotoOne.Metadata.ImageHeight;
                    entity.WidthPix = jpgPhotoOne.Metadata.ImageWidth;
                }


                iSun.FileUploadMessage file = new iSun.FileUploadMessage();

                file.FileName = fi.Name;// "IMG_0467.jpg";
                file.FileData = new System.IO.FileStream(fi.FullName, System.IO.FileMode.Open);
                entity.FileSize = (int)file.FileData.Length;
                string json = ZX.Common.Globals.ObjectToJSON(entity);
                file.SavePath = json;
                file.JsonData = json;
                _uploadCompleted = false;
                _uploadWatchThread = new System.Threading.Thread(UpdateFileUploadInfo);
                _uploadWatchThread.Start(file);

                //var _client = new iSun.UpLoadServiceClient();
                _client.UploadFileAsync(file.FileName, file.JsonData, file.SavePath, file.FileData);
                _client.UploadFileCompleted += new EventHandler<AsyncCompletedEventArgs>(client_UploadFileCompleted);
            }
            catch(Exception ex)
            {
                ZX.Log.XTrace.WriteLine("----------------------------上传---begin---------------------------------");
                ZX.Log.XTrace.WriteLine(System.DateTime.Now.ToString());
                ZX.Log.XTrace.WriteLine(fi.FullName);
                ZX.Log.XTrace.WriteLine(ex.Message);
                ZX.Log.XTrace.WriteLine("-------------------------------end-----------------------------------");
                //if (_filelenth > -1)
                //{
                //    if (_fileIndex < _filelenth)
                //    {
                //        _fileIndex = _fileIndex + 1;
                //        UploadFile(_list[_fileIndex].file, _list[_fileIndex].stepN);
                //    }
                //}
            }
                //iSun.UpLoadServiceClient ser = new iSun.UpLoadServiceClient();
            //iSun.IUpLoadService channel = ser.ChannelFactory.CreateChannel();

            //channel.UploadFile(file);
            //_uploadCompleted = true ; 
        }


        void DirRemane(System.IO.DirectoryInfo dir)
        {
            foreach(System.IO.DirectoryInfo _dir in dir.GetDirectories())
            {
                if (_dir.Name.ToLower() == "mv")
                {
                    _dir.MoveTo(_dir.FullName.ToLower().Replace("mv", "vedio"));
                }
                if (_dir.Name == "原图")
                {
                    _dir.MoveTo(_dir.FullName.Replace("原图","images"));
                }
                DirRemane(_dir);
            }
        }

        void client_UploadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            _uploadCompleted = true;

            //if (_filelenth > -1)
            //{
            //    if (_fileIndex < _filelenth-1)
            //    {
            //        _fileIndex = _fileIndex + 1;
            //        UploadFile(_list[_fileIndex].file, _list[_fileIndex].stepN);
            //    }
            //}
            progressBar1.Invoke(_updateProcessBar, 0);
            this.lblInfo.Invoke(_updateLabel, 0, 0);
            lblFileName.Invoke(_updateFileName, "");

            webBrowser1.Document.InvokeScript("fnRefresh");
        }

        void UpdateFileUploadInfo(object obj)
        {
            iSun.FileUploadMessage uploadData = obj as iSun.FileUploadMessage;
            iSun.Entity.ProductImage entity = ZX.Common.Globals.JSonToObject<iSun.Entity.ProductImage>(uploadData.SavePath);

            //iSun.UpLoadServiceClient _c = new iSun.UpLoadServiceClient();
            //iSun.UpLoadServiceClient ser = new iSun.UpLoadServiceClient();
            //iSun.IUpLoadService channel = ser.ChannelFactory.CreateChannel();
            //channel.GetUploadFileInfo(entity.FilePath + entity.fileName);
            var uploadSize = 4096;// channel.GetUploadFileInfo(entity.FilePath + entity.fileName); //_c.GetUploadFileInfo(entity.FilePath+entity.fileName);
            var totalSize =entity.FileSize;
            int i = 0;
            
            lblFileName.Invoke(_updateFileName, entity.fileName);
            while (uploadSize < entity.FileSize)
            {
                i = i + 1;
                double process = ((double)uploadSize / entity.FileSize) * 100;
                progressBar1.Invoke(_updateProcessBar, (int)process);
                lblInfo.Invoke(_updateLabel, uploadSize, totalSize);
               
                System.Threading.Thread.Sleep(500);
                if (_uploadCompleted)
                {
                    progressBar1.Invoke(_updateProcessBar, progressBar1.Maximum);
                    this.lblInfo.Invoke(_updateLabel, totalSize, totalSize);
                    lblFileName.Invoke(_updateFileName, "");
                    uploadData.FileData.Close();
                    try
                    {
                      
                        if (System.IO.File.Exists(entity.FullName.Replace(entity.fileName, "") + "Uploaded_" +entity.fileName))
                        {
                            System.IO.File.Delete(entity.FullName.Replace(entity.fileName, "") + "Uploaded_" + entity.fileName);
                        }
                        
                        System.IO.FileInfo fi = new System.IO.FileInfo(entity.FullName);
                        fi.MoveTo(entity.FullName.Replace(entity.fileName, "") + "Uploaded_" + entity.fileName);
                        webBrowser1.Document.InvokeScript("fnRefresh");
                    }
                    catch (Exception e)
                    {
                    }
                    progressBar1.Invoke(_updateProcessBar,0);
                    this.lblInfo.Invoke(_updateLabel, 0, 0);
                    lblFileName.Invoke(_updateFileName, "");
                    
                    //if (_filelenth > -1)
                    //{
                    //    if (_fileIndex < _filelenth)
                    //    {
                    //        _fileIndex =_fileIndex+ 1;
                    //        UploadFile(_list[_fileIndex].file,_list[_fileIndex].stepN);
                    //    }
                    //}
                    return;
                }
                else
                {
                    uploadSize = (512+218) * i * 1024 * 1;
                    //uploadSize =_client.GetUploadFileInfo("\\upload\\photo1\\"+entity.FilePath + entity.fileName);// i * 4096;// 
                    continue;
                }
            }
   
        }


        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (_uploadWatchThread == null)
            {
                return;
            }
            if (!_uploadWatchThread.Join(500))
            {
                try
                {
                    _uploadWatchThread.Abort();
                }
                catch
                { }
            }
        }

        #endregion

        private void button7_Click(object sender, EventArgs e)
        {
            DataAction.SynSerivceDataToClient();
        }

        private void btnUploadInitFiles_Click(object sender, EventArgs e)
        {
            //DirRemane(new System.IO.DirectoryInfo(ConfigurationManager.AppSettings["filePath"]));
            InitProductSN();
            UploadFile();
            //UploadFile(1);
        }

        int _filelenth = -1;
        int _fileIndex = 0;
        EntityFile _cureentFile = null;
        IList<EntityFile> _list = null;
        private void UploadFile()
        {
            IList<EntityFile> list = new List<EntityFile>();
            GetFiles(new System.IO.DirectoryInfo(ConfigurationManager.AppSettings["filePath"]),list,0);
           // GetFiles(new System.IO.DirectoryInfo(ConfigurationManager.AppSettings["filePath1"]), list, 1);
            _list = list;
            _filelenth = list.Count;
            _fileIndex = 0;
            if (_filelenth > 0)
            {
                UploadFile(list[_fileIndex].file, list[_fileIndex].stepN);
            }
            //this.lblFileName.Text = "";
            //foreach (System.IO.FileInfo file in list)
            //{
            //    this.lblFileName.Text = file.Name;
            //    UploadFile(file, stepN);
            //    while (file.Name == this.lblFileName.Text)
            //    {
            //        System.Threading.Thread.Sleep(50);
            //        continue;
            //    }
            //}
        }
        /// <summary>
        /// 初始化ProductName 
        /// </summary>
        void InitProductSN()
        {
            System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(ConfigurationManager.AppSettings["filePath"]);
            IList<ProductPhotoEnitty> _list = new List<ProductPhotoEnitty>();
            foreach (System.IO.DirectoryInfo _dir in dir.GetDirectories())
            {
                ProductPhotoEnitty pEntity = new ProductPhotoEnitty();
                string[] _sn=_dir.Name.Split('_');
                pEntity.SN =_sn[0];
                pEntity.ProductName = _dir.Name;
                pEntity.AddTime = System.DateTime.Now;
                pEntity.AddUser = Guid.Empty;
                pEntity.ID = new Guid();
                pEntity.Vendor_id = _sn.Length>1?(string.IsNullOrEmpty(_sn[1])?0:Convert.ToInt32(_sn[1])):0;
                _list.Add(pEntity);
            }

            iSun.UpLoadServiceClient ser = new iSun.UpLoadServiceClient();
            iSun.IUpLoadService channel = ser.ChannelFactory.CreateChannel();
            foreach (var _li in _list)
            {
                IList<ProductPhotoEnitty> __list = new List<ProductPhotoEnitty>();
                __list.Add(_li);
                channel.UploadProduct(ZX.Common.Globals.ListToJson<ProductPhotoEnitty>(__list));
            }
        }

        private void BacthChangDirName()
        {
            System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(ConfigurationManager.AppSettings["filePath"]);
            IList<ProductPhotoEnitty> _list = new List<ProductPhotoEnitty>();
            foreach (System.IO.DirectoryInfo _dir in dir.GetDirectories())
            {
                if (!_dir.Name.Contains("_"))
                {
                    _dir.MoveTo(_dir.FullName + "_1");
                }
            }
        }

        public void BachtChangDirName2()
        {
            System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(ConfigurationManager.AppSettings["filePath"]);
            IList<ProductPhotoEnitty> _list = new List<ProductPhotoEnitty>();
            foreach (System.IO.DirectoryInfo _dir in dir.GetDirectories())
            {
                if (_dir.Name.Contains("_1"))
                {
                    _dir.MoveTo(_dir.FullName.Replace("_1",""));
                }
            }
        }

        private void BacthChangFileName()
        {
            string  rootPath = ConfigurationManager.AppSettings["filePath"];
            System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(ConfigurationManager.AppSettings["filePath"]);
            IList<EntityFile> _list = new List<EntityFile>();
            GetFiles(dir, _list, 0);
            foreach (EntityFile entity in _list)
            {
                string path = entity.file.FullName.ToLower().Replace(rootPath.ToLower(), "");
                string[] _str = path.Split('\\');
                string sn = _str[0];
                if(entity.file.Name.Contains(sn))
                {
                    continue;
                }
                if (_str.Length < 2)
                {
                    continue;
                }
                string __ttype = "_P_";
                try
                {
                    switch (_str[1])
                    {
                        case "images":
                            //sourcePath = sourcePath + "\\images\\";
                            __ttype = "_P_";
                            break;
                        case "thumb":
                            //sourcePath = sourcePath + "\\thumb\\";
                            __ttype = "_T_";
                            break;
                        case "vedio":
                            //sourcePath = sourcePath + "\\vedio\\";
                            __ttype = "_V_";
                            break;
                        default:
                            //sourcePath = sourcePath + "\\images\\";
                            __ttype = "_P_";
                            break;
                    }
                    entity.file.MoveTo(entity.file.DirectoryName + "\\" + sn + __ttype + entity.file.Name);
                }
                catch (Exception ex)
                {
                  
                }
            }
        }

        //撤消更新的文件名
        void fileRename(System.IO.DirectoryInfo dir)
        {
            try
            {
                foreach (var file in dir.GetFiles())
                {
                    file.MoveTo(file.FullName.Replace("Uploaded_", ""));
                }
                foreach (var _dir in dir.GetDirectories())
                {
                    fileRename(_dir);
                }
            }
            catch (Exception ex)
            {
                ZX.Log.XTrace.WriteLine("-------------------------------begin---------------------------------");
                ZX.Log.XTrace.WriteLine(System.DateTime.Now.ToString());
                ZX.Log.XTrace.WriteLine(dir.FullName);
                ZX.Log.XTrace.WriteLine(ex.Message);
                ZX.Log.XTrace.WriteLine("-------------------------------end-----------------------------------");
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button7_Click_2(object sender, EventArgs e)
        {
            fileRename(new System.IO.DirectoryInfo(ConfigurationManager.AppSettings["filePath"]));
        }

        /// <summary>
        /// 第一步
        /// </summary>
        private void Step(int step)
        {
           //获取目录
            DeleteDir(step);
            //更新产品
            if (step == 0)
            {
                InitProductSN();
            }
                //拷文件
            CopyFiles(step);
        }



        /// <summary>
        /// 
        /// </summary>
        private void DeleteDir(int step)
        {
            System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(ConfigurationManager.AppSettings["filePath"]);

            IList<ProductPhotoEnitty> _list = new List<ProductPhotoEnitty>();
            foreach (System.IO.DirectoryInfo _dir in dir.GetDirectories())
            {
                ProductPhotoEnitty pEntity = new ProductPhotoEnitty();
                pEntity.SN = _dir.Name;
                pEntity.ProductName = _dir.Name;
                pEntity.AddTime = System.DateTime.Now;
                pEntity.AddUser = Guid.Empty;
                pEntity.ID = new Guid();
                pEntity.Vendor_id = 10000;
                _list.Add(pEntity);
            }
            foreach (var _li in _list)
            {
                try
                {

                    if (System.IO.Directory.Exists(ConfigurationManager.AppSettings[step == 0 ? "targetPath1" : "targetPath2"] + _li.SN))
                    {
                        System.IO.DirectoryInfo _tempdir = new System.IO.DirectoryInfo(ConfigurationManager.AppSettings[step == 0 ? "targetPath1" : "targetPath2"] + _li.SN);
                        _tempdir.Delete(true);
                    }
                    System.IO.Directory.CreateDirectory(ConfigurationManager.AppSettings[step == 0 ? "targetPath1" : "targetPath2"] + _li.SN);
                }
                catch (Exception ex) {
                    ZX.Log.XTrace.WriteLine("----------------------------上传---begin---------------------------------");
                    ZX.Log.XTrace.WriteLine(System.DateTime.Now.ToString());
                    ZX.Log.XTrace.WriteLine(ConfigurationManager.AppSettings[step == 0 ? "targetPath1" : "targetPath2"] + _li.SN);
                    ZX.Log.XTrace.WriteLine(ex.Message);
                    ZX.Log.XTrace.WriteLine("-------------------------------end-----------------------------------");
                    return;
                }
            }
           
        }

        /// <summary>
        /// 拷文件
        /// </summary>
        /// <param name="stepN"></param>
        private void CopyFiles(int stepN)
        {
            IList<EntityFile> list = new List<EntityFile>();
            string webFileRootPath = ConfigurationManager.AppSettings[stepN == 0 ? "targetPath1" : "targetPath2"];
            string filePath = stepN == 0 ? ConfigurationManager.AppSettings["filePath"] : ConfigurationManager.AppSettings["filePath1"];
            GetFiles(new System.IO.DirectoryInfo(filePath), list, 0);
          
            int _fileCount = list.Count;
            int _currentNum = 0;
            this.progressBar1.Maximum = _fileCount;
            foreach (EntityFile file in list)
            {
                _currentNum++;
                string _filePath = file.file.FullName.ToLower().Replace(filePath.ToLower(), "");//相对路径
                string _webPath = (stepN == 0 ? "\\upload\\photo\\" : "\\upload\\photo1\\") + file.file.FullName.ToLower().Replace(filePath.ToLower(), "");//相对路径
                
                _updateFileName(_filePath);
                _updateProcessBar(_currentNum);
                _updateLabel(_currentNum, _fileCount);
                #region 保存图片数据
                try
                {
                    System.IO.FileInfo fi = file.file;
                    string _path = stepN == 0 ? ConfigurationManager.AppSettings["filePath"] : ConfigurationManager.AppSettings["filePath1"];
                    ProductImage entity = new ProductImage();

                    entity.fileName = fi.Name;
                    entity.FilePath = fi.FullName.Replace(_path, "").Replace(fi.Name, "");
                    entity.SN = entity.FilePath.Split('\\')[0];
                    entity.DirectoryName = fi.DirectoryName.Replace(_path, "");
                    entity.FullName = fi.FullName;
                    entity.StepN = stepN;

                    entity.SourceFileName = fi.Name;
                    entity.FileType = fi.Extension;

                    entity.ImageType = "0";
                    entity.ImageType = entity.FilePath.Contains("\\thumb\\") ? "1" : entity.ImageType;
                    entity.ImageType = entity.FilePath.Contains("\\vedio\\") ? "2" : entity.ImageType;
                    //entity.ImageType = 

                    if (fi.Extension.ToLower().IndexOf("jpg") > -1)
                    {
                        Fotofly.JpgPhoto jpgPhotoOne = ZX.Common.IPTC.ReadImageInfo.Load(fi.FullName);
                        entity.Summary = jpgPhotoOne.Metadata.Comment;
                        entity.CreationSoftware = jpgPhotoOne.Metadata.CreationSoftware;
                        entity.CameraManufacturer = jpgPhotoOne.Metadata.CameraManufacturer;
                        entity.CameraModel = jpgPhotoOne.Metadata.CameraModel;
                        entity.Copyright = jpgPhotoOne.Metadata.Copyright;
                        entity.HeigthPix = jpgPhotoOne.Metadata.ImageHeight;
                        entity.WidthPix = jpgPhotoOne.Metadata.ImageWidth;
                    }
                    entity.FilePath = _webPath;
                    entity.FileSize = (int)fi.Length;
                    ZX.BLL.Extend.BaseBussnies bll = new ZX.BLL.Extend.BaseBussnies();
                    bll.RunSqlCommand("delete from gs_ProductImage where filePath ='" + _webPath + "'");


                    IList<iSun.Entity.ProductPhotoEnitty> __list = bll.GetEntitys<iSun.Entity.ProductPhotoEnitty>("SN='" + entity.SN + "'");
                    if (__list != null)
                    {
                        entity.ProductID = __list[0].ID;
                    }

                    bll.entity = entity;
                    bll.Insert();
                }
                catch (Exception ex)
                {
                    ZX.Log.XTrace.WriteLine("----------------------------上传---begin---------------------------------");
                    ZX.Log.XTrace.WriteLine(System.DateTime.Now.ToString());
                    ZX.Log.XTrace.WriteLine(file.file.FullName);
                    ZX.Log.XTrace.WriteLine(ex.Message);
                    ZX.Log.XTrace.WriteLine("-------------------------------end-----------------------------------");
                    continue;
                }
                #endregion

                #region 拷文件
                if (!System.IO.Directory.Exists(ZX.Common.FileHelper.GetFileDir(webFileRootPath + _filePath)))
                {
                    System.IO.Directory.CreateDirectory(ZX.Common.FileHelper.GetFileDir(webFileRootPath + _filePath));
                }
                file.file.CopyTo(webFileRootPath + _filePath,true);


                #endregion
            }
        }


        /// <summary>
        /// 获取目录下所有文件
        /// </summary>
        /// <param name="dir"></param>
        /// <param name="list"></param>
        /// <param name="stepN"></param>
        private void GetFiles(System.IO.DirectoryInfo dir, IList<EntityFile> list, int stepN)
        {
            foreach (var file in dir.GetFiles())
            {
                EntityFile entity = new EntityFile();
                if (file.Extension.Contains("db"))
                {
                    continue;
                }
                if (file.FullName.Contains("vedio"))
                {
                    if (file.Extension.Contains("zip")||file.Extension.Contains("jpg"))
                    {
                        if (file.Name.Contains("Uploaded_"))
                        {
                            continue;
                        }
                        entity.stepN = stepN;
                        entity.file = file;
                        list.Add(entity);
                    }
                }
                else
                {
                    if (file.Name.Contains("Uploaded_"))
                    {
                        continue;
                    }
                    entity.stepN = stepN;
                    entity.file = file;
                    list.Add(entity);
                }
            }
            foreach (var _dir in dir.GetDirectories())
            {
                GetFiles(_dir, list, stepN);
            }
        }

        class EntityFile
        {
            public int stepN
            {
                get;
                set;
            }
            public System.IO.FileInfo file
            {
                get;
                set;
            }
        }

        private void button7_Click_1(object sender, EventArgs e)
        {
            BacthChangFileName();
        }

        private void button9_Click(object sender, EventArgs e)
        {
            int _step = this.cbkInitDataFlag.Checked ? 1 : 0;
            Step(_step);
        }

        private void btnInitDirName_Click(object sender, EventArgs e)
        {
            System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(ConfigurationManager.AppSettings["filePath"]);
            DirRemane(dir);
        }

        /// <summary>
        /// 
        /// </summary>
        private void UpdateFtpServer()
        {
            //ftp ftpClient = new ftp(@"ftp://localhost/", "user", "password");

            //ftpClient.upload("etc/test.txt", @"C:\Users\metastruct\Desktop\test.txt");

            //ftpClient = null;
        }


        private void button1_Click_1(object sender, EventArgs e)
        {
            this.folderBrowserDialog1.ShowDialog();
            string _folder = this.folderBrowserDialog1.SelectedPath;
            if (_folder == "")
            {
                return;
            }
            System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(_folder);
            foreach (var file in dir.GetFiles())
            {
                string  _dir  = file.Name.Replace(file.Extension, "");
                if (!System.IO.Directory.Exists(ConfigurationManager.AppSettings["filePath"] + dir + "\\vedio"))
                {
                    System.IO.Directory.CreateDirectory(ConfigurationManager.AppSettings["filePath"] + _dir + "\\vedio");
                }
                file.CopyTo(ConfigurationManager.AppSettings["filePath"] + _dir + "\\vedio\\" + file.Name);
            }
            MessageBox.Show("初始化完成！");
        }

        #region 供应商变更
        private void comboBox1_TextChanged(object sender, EventArgs e)
        {
            VendorChanged();
        }


        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            VendorChanged();
        }


        private void VendorChanged()
        {
            iSun.App.UserInfo.CurrentVendor_id = this.comboBox1.Text.Trim().Split('_')[0];
            this.webBrowser1.Document.GetElementById("CurrentVendor_ID").SetAttribute("value", iSun.App.UserInfo.CurrentVendor_id);
            this.webBrowser1.Document.InvokeScript("GetTreeData");
        }
        #endregion 

        private void button7_Click_3(object sender, EventArgs e)
        {
            this.folderBrowserDialog1.ShowDialog();
            string _folder = this.folderBrowserDialog1.SelectedPath;
            if (_folder == "")
            {
                return;
            }
            System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(_folder);
            IList<EntityFile> list = new List<EntityFile>();
            GetFiles(dir, list, 0);
            string[] str = {"images"};
            foreach (EntityFile enity in list)
            {
                try
                {
                    string[] _path1 = enity.file.FullName.Split(str, StringSplitOptions.None);
                    string sn = enity.file.Name.Split('_')[0];
                    string _path2 = "D:\\TEMP\\" + sn + "\\images\\";
                    if (!System.IO.Directory.Exists(_path2))
                    {
                        System.IO.Directory.CreateDirectory(_path2);
                    }
                    enity.file.CopyTo(_path2 + enity.file.Name);
                }
                catch { }
            }

           
        }

        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {

        }
    }
}
